import { ElMessage, ElNotification } from "element-plus";

/**
 * @description 接收数据流生成 blob，创建链接，下载文件
 * @param {Function} api 导出表格的api方法 (必传)
 * @param {String} tempName 导出的文件名 (必传)
 * @param {Object} params 导出的参数 (默认{})
 * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
 * @param {String} fileType 导出的文件格式 (默认为.xlsx)
 * */
interface DownloadParams {
  api: (param: any) => Promise<any>;
  tempName: string;
  params?: any;
  isNotify?: boolean;
  fileType?: string;
}
export const useDownload = async (downloadParams: DownloadParams) => {
  const { api, tempName, params, isNotify = true, fileType = ".xlsx" } = downloadParams;
  if (isNotify) {
    ElNotification({
      title: "温馨提示",
      message: "如果数据庞大会导致下载缓慢哦，请您耐心等待！",
      type: "info",
      duration: 3000,
    });
  }
  try {
    const res = await api(params);
    const blob = new Blob([res]);
    // 兼容 edge 不支持 createObjectURL 方法
    if ("msSaveOrOpenBlob" in navigator) {
      return (window.navigator as any).msSaveOrOpenBlob(
        blob,
        tempName + fileType
      );
    }
    const blobUrl = window.URL.createObjectURL(blob);
    const exportFile = document.createElement("a");
    exportFile.style.display = "none";
    exportFile.download = `${tempName}${fileType}`;
    exportFile.href = blobUrl;
    document.body.appendChild(exportFile);
    exportFile.click();
    // 去除下载对 url 的影响
    document.body.removeChild(exportFile);
    window.URL.revokeObjectURL(blobUrl);
  } catch (error) {
    console.log(error);
  }
};
//  通过url 下载图片
export const useDownloadImgByUrl = async (imgSrc: string, name: string) => {
  try {
    var image = new Image();
    // 解决跨域 Canvas 污染问题
    image.setAttribute("crossOrigin", "anonymous");
    image.onload = function () {
      var canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      var context = canvas.getContext("2d");
      if (context) {
        context.drawImage(image, 0, 0, image.width, image.height);
      } else {
        throw new Error("无法获取 canvas 的 2D 上下文");
      }
      var url = canvas.toDataURL("image/png"); // 得到图片的base64编码数据
      var a = document.createElement("a"); // 生成一个a元素
      var event = new MouseEvent("click"); // 创建一个单击事件
      a.download = name || "photo"; // 设置图片名称
      a.href = url; // 将生成的URL设置为a.href属性
      a.dispatchEvent(event); // 触发a的单击事件
    };
    image.src = imgSrc;
  } catch (error) {
    ElMessage.error("下载失败");
  }
};

/**
 * 通过 URL 下载文件（支持下载图片 pdf 等）
 * @param url 文件地址
 * @param name 下载后的文件名
 */
export const useDownloadFile = async (url: string, filename: string) => {
  try {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (xhr.status === 200) {
        const blob = new Blob([xhr.response]);
        const url = URL.createObjectURL(blob);
        saveAs(blob, filename);
      }
    };
    xhr.send();
  } catch (error) {
    ElMessage.error("下载失败");
  }
};
/**
 * 保存 Blob 数据为文件
 * @param blob 要保存的 Blob 数据
 * @param filename 文件名
 */
const saveAs = (blob: Blob, filename: string): void => {
  if ("msSaveOrOpenBlob" in window.navigator) {
    // 兼容 IE 或 Edge
    (window.navigator as any).msSaveOrOpenBlob(blob, filename);
  } else {
    const link = document.createElement("a");
    const body = document.querySelector("body");
    if (!body) return;
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.style.display = "none";
    body.appendChild(link);
    link.click();
    body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  }
};
